/**
 * Created by fish on 16/10/26.
 * 上级分类选择 radio
 */

layui.use(['tree', 'form', 'tools'], function(){
    $ = layui.jquery;
    form = layui.form();
    tools = layui.tools;
    var categoryTypeElem = $('input[name="category_type"]') || 1;

    getCategoryList(categoryTypeElem.val());

    form.on('select(category_type)', function(data){
        $('input[name="categroy_id"]').val(0);
        $('.add-category>span').html('选择分类');
        var pids = $('input[name="product_ids"]');
        var pidsBlock = $('.category-product-block');
        switch(data.value){
            case '1':
                pids.val('');
                if(!pidsBlock.hasClass('layui-hide')){
                    pidsBlock.addClass('layui-hide')
                }
                break;
            case '2':
                if(pidsBlock.hasClass('layui-hide')){
                    pidsBlock.removeClass('layui-hide')
                }
                pids.val(pids.attr('data-value'));
                break;
        }
        categoryTypeElem.val(data.value);
        getCategoryList(data.value);
    });


    //展开分类
    $('.add-category').on('click', function(){
        $('.category-list').removeClass('layui-hide');
    });

    function getCategoryList(type, elem){
        $.ajax({
            data: {type:type},
            dataType: 'json',
            type: 'get',
            url: '/api/category/category_list/',
            error: function(){
                layer.msg('系统错误');
            },
            success: function(json){
                var list = json.data.list;
                var elem = elem || '#category-tree';
                $(elem).empty();
                if(!tools.isEmpty(list) && list.length > 0) {
                    layui.tree({
                        elem: elem,
                        check: 'radio',
                        nodes: list,
                        click: function (node) {
                            $('input[name="categroy_id"]').val(node.id);
                            $('.add-category>span').html(node.category_name);
                            layer.msg(node.category_name);
                            $('.category-list').addClass('layui-hide');
                        }
                    });
                }else{
                    $('.category-list').addClass('layui-hide');
                }
            }
        });
    }
});